package me.flyray.biz.thymeleaf.modules.goods.biz;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.qr.request.QrGoodsRequestParam;
import com.github.wxiaoqi.security.common.qr.request.QrQueryGoodsParam;
import com.github.wxiaoqi.security.common.qr.request.QrThenPayStatisticsParam;
import com.github.wxiaoqi.security.common.util.EntityUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import me.flyray.biz.thymeleaf.feign.CrmFeign;
import me.flyray.biz.thymeleaf.modules.goods.entity.QrGoodsInfo;
import me.flyray.biz.thymeleaf.modules.goods.entity.QrGoodsScanningStatistics;
import me.flyray.biz.thymeleaf.modules.goods.mapper.QrGoodsInfoMapper;
import me.flyray.biz.thymeleaf.modules.goods.mapper.QrGoodsScanningStatisticsMapper;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 商品管理
 * @author he
 * @date 2018-09-12 14:11:56
 */
@Service
public class QrGoodsInfoBiz extends BaseBiz<QrGoodsInfoMapper,QrGoodsInfo> {
	
	private static final Logger logger = (Logger) LoggerFactory.getLogger(QrGoodsInfoBiz.class);
	
	@Autowired
	private QrGoodsScanningStatisticsMapper qrGoodsScanningStatisticsMapper;
	@Autowired
	private CrmFeign crmFeign;
	
	public TableResultResponse<QrGoodsInfo> queryList(QrQueryGoodsParam param) {
		Example example = new Example(QrGoodsInfo.class);
		Criteria criteria = example.createCriteria();
		
		if (param.getPlatformId() != null && param.getPlatformId().length() > 0) {
			criteria.andEqualTo("platformId", param.getPlatformId());
		}
		if (param.getMerchantId() != null && param.getMerchantId().length() > 0) {
			criteria.andEqualTo("merchantId", param.getMerchantId());
		}
		if (param.getGoodsId() != null && param.getGoodsId().length() > 0) {
			criteria.andEqualTo("goodsId", param.getGoodsId());
		}
		Page<QrGoodsInfo> result = PageHelper.startPage(param.getPage(), param.getLimit());
		List<QrGoodsInfo> list = mapper.selectByExample(example);
		TableResultResponse<QrGoodsInfo> table = new TableResultResponse<>(result.getTotal(), list);
		return table;
	}
	
	/**
	 * 记录扫描次数
	 * @param request
	 * @return
	 */
	public QrGoodsInfo recordingScanningNum(@RequestBody Map<String, Object> params){
		logger.info("记录扫描次数请求.......{}",params);
		QrGoodsInfo qrGoodsInfo = new QrGoodsInfo();
		qrGoodsInfo.setPlatformId((String) params.get("platformId"));
		qrGoodsInfo.setMerchantId((String) params.get("merchantId"));
		qrGoodsInfo.setGoodsId((String) params.get("goodsId"));
		QrGoodsInfo selectQrGoodsInfo = mapper.selectOne(qrGoodsInfo);
		if(null != selectQrGoodsInfo){
			Long scanCount = selectQrGoodsInfo.getScanCount();
			if(scanCount == 0){
				selectQrGoodsInfo.setFirstScanDate(new Date());
			}
			selectQrGoodsInfo.setScanCount(scanCount + 1);
			mapper.updateByPrimaryKey(selectQrGoodsInfo);
			
			//记录扫描记录
			QrGoodsScanningStatistics qrGoodsScanningStatistics = new QrGoodsScanningStatistics();
			qrGoodsScanningStatistics.setGoodsId((String) params.get("goodsId"));
			qrGoodsScanningStatistics.setPlatformId((String) params.get("platformId"));
			qrGoodsScanningStatistics.setMerchantId((String) params.get("merchantId"));
			qrGoodsScanningStatistics.setUserWechatOpenId((String) params.get("openid"));
			qrGoodsScanningStatistics.setScanningTime(new Date());
			qrGoodsScanningStatisticsMapper.insert(qrGoodsScanningStatistics);
		}
		return selectQrGoodsInfo;
	}
	
	
	/**
	 * 添加
	 * @param param
	 * @return
	 */
	public QrGoodsInfo addGoodsInfo(QrGoodsRequestParam param) {
		logger.info("添加商品,请求参数。。。{}"+param);
		QrGoodsInfo reqConfig = new QrGoodsInfo();
		QrGoodsInfo config1 = null;
		try {
			BeanUtils.copyProperties(reqConfig, param);
			config1 = mapper.selectOne(reqConfig);
			if (config1 == null) {
				mapper.insert(reqConfig);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return config1;
	}
	
	
	/**
	 * 修改
	 * @param param
	 * @return
	 */
	public QrGoodsInfo updateGoodsInfo(QrGoodsRequestParam param) {
		logger.info("修改商品,请求参数。。。{}"+param);
		QrGoodsInfo reqConfig = new QrGoodsInfo();
		QrGoodsInfo config1 = null;
		try {
			BeanUtils.copyProperties(reqConfig, param);
			reqConfig.setId(Long.valueOf(param.getId()));
			config1 = mapper.selectByPrimaryKey(Long.valueOf(param.getId()));
			if (config1 != null) {
				mapper.updateByPrimaryKeySelective(reqConfig);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return config1;
	}
	
	/**
	 * 删除
	 * @param param
	 * @return
	 */
	public QrGoodsInfo deleteGoodsInfo(QrGoodsRequestParam param) {
		logger.info("删除商品,请求参数。。。{}"+param);
		QrGoodsInfo reqConfig = new QrGoodsInfo();
		QrGoodsInfo config1 = null;
		try {
			BeanUtils.copyProperties(reqConfig, param);
			reqConfig.setId(Long.valueOf(param.getId()));
			config1 = mapper.selectByPrimaryKey(Long.valueOf(param.getId()));
			if (config1 != null) {
				mapper.delete(reqConfig);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return config1;
	}
	
	/**
	 * 导入商品
	 * @param param
	 */
	public void importGoodsList(Map<String, Object> param) {
		String platformId = (String) param.get("platformId");
		List<Map<String, Object>> list = (List<Map<String, Object>>) param.get("rows");
		if (list != null && list.size() > 0) {
			for (Map<String, Object> map : list) {
				QrGoodsInfo goodsInfo = new QrGoodsInfo();
				goodsInfo.setPlatformId(platformId);
				goodsInfo.setGoodsId((String) map.get("商品编号"));
				goodsInfo.setGoodsPrice(new BigDecimal((String) map.get("商品价格")));
				goodsInfo.setStorageDate(new Date());
				goodsInfo.setScanCount(new Long((long)0));
				goodsInfo.setPayCount(new Long((long)0));
				goodsInfo.setPwdStartBit(0);
				goodsInfo.setPwdLibrary((String) map.get("密码库"));
				goodsInfo.setOperatorId("qrtest");
				mapper.insert(goodsInfo);
			}
		}
	}
	
	/**
	 * 二维码
	 * @param param
	 */
	public Map<String, Object> createGoodsQr(Map<String, Object> param) {
		Map<String, Object> respMap = new HashMap<>();
		String idString = (String) param.get("idStr");
		String urlStr = "https://www.huoyuanshequ.com/api/api/thymeleaf/jumpPay?";
		if (idString != null) {
			String[] strs = idString.split(",");
			for (String string : strs) {
				logger.info("选中的goodsId "+string);
				QrGoodsInfo goodsInfo = new QrGoodsInfo();
				goodsInfo.setGoodsId(string);
				QrGoodsInfo goodsInfo1 = mapper.selectOne(goodsInfo);
				if (goodsInfo1 != null) {
					String platformId = goodsInfo1.getPlatformId();
					String merchantId = goodsInfo1.getMerchantId();
					String goodsId = goodsInfo1.getGoodsId();
					BigDecimal goodsPrice = goodsInfo1.getGoodsPrice();
					String goodsPic = goodsInfo1.getGoodsPic();
					//二维码内容
					String text = urlStr+"goodsId="+goodsId+"&goodsPic="+goodsPic+"&goodsPrice="+goodsPrice+"&platformId="+platformId+"&merchantId="+merchantId;
					
					//获取二维码对象 
					OutputStream os;
					String qrImgFile = "d:/qrcode/targetimg/" + goodsId + ".png"; 
					try {
						File qrImgF = new File(qrImgFile);
						if (!qrImgF.getParentFile().exists()) {
							qrImgF.setWritable(true, false);
							qrImgF.getParentFile().mkdirs();
			        	}
						os = new FileOutputStream(qrImgF);
						createQrCode(os, text, 1500, "PNG");
						
						respMap.put("path", "d:/qrcode/targetimg/");
					} catch (Exception e) {
						e.printStackTrace();
					} 
				}
			}
		}
		return respMap;
	}
	
	/**
	 * 保存二维码到本地
	 * @param outputStream
	 * @param content
	 * @param qrCodeSize
	 * @param imageFormat
	 * @return
	 * @throws WriterException
	 * @throws IOException
	 */
	public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException{  
        //设置二维码纠错级别ＭＡＰ
        Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();  
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  // 矫错级别  
        QRCodeWriter qrCodeWriter = new QRCodeWriter();  
        //创建比特矩阵(位矩阵)的QR码编码的字符串  
        BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);  
        // 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
        int matrixWidth = byteMatrix.getWidth();  
        BufferedImage image = new BufferedImage(matrixWidth-200, matrixWidth-200, BufferedImage.TYPE_INT_RGB);  
        image.createGraphics();  
        Graphics2D graphics = (Graphics2D) image.getGraphics();  
        graphics.setColor(Color.WHITE);  
        graphics.fillRect(0, 0, matrixWidth, matrixWidth);  
        // 使用比特矩阵画并保存图像
        graphics.setColor(Color.BLACK);  
        for (int i = 0; i < matrixWidth; i++){
            for (int j = 0; j < matrixWidth; j++){
                if (byteMatrix.get(i, j)){
                    graphics.fillRect(i-100, j-100, 1, 1);  
                }
            }
        }
        return ImageIO.write(image, imageFormat, outputStream);  
}  
	
	/**
	 * 详情
	 * @param param
	 * @return
	 */
	public QrGoodsInfo queryGoodsInfo(Map<String, Object> param) {
		String idString = (String) param.get("goodsId");
		String platformId = (String) param.get("platformId");
		QrGoodsInfo goodsInfo = new QrGoodsInfo();
		goodsInfo.setGoodsId(idString);
		goodsInfo.setPlatformId(platformId);
		QrGoodsInfo goodsInfo1 = mapper.selectOne(goodsInfo);
		return goodsInfo1;
	}
	
	/**
	 * 获取商品密码
	 * @param param
	 * @return
	 */
	public QrGoodsInfo obtainGoodsPwd(Map<String, Object> params){
		logger.info("获取商品密码请求.......{}",params);
		QrGoodsInfo qrGoodsInfo = new QrGoodsInfo();
		qrGoodsInfo.setPlatformId((String) params.get("platformId"));
		qrGoodsInfo.setMerchantId((String) params.get("merchantId"));
		qrGoodsInfo.setGoodsId((String) params.get("goodsId"));
		QrGoodsInfo selectQrGoods = mapper.selectOne(qrGoodsInfo);
		if(null != selectQrGoods){
			//更新密码起始位
			Integer pwdStartBit = selectQrGoods.getPwdStartBit();
			String pwdLibrary = selectQrGoods.getPwdLibrary();
			String lastPwd = selectQrGoods.getLastPwd();
			if(StringUtils.isEmpty(lastPwd)){
				//最后一次使用的密码为空，则本次为第一次使用，起始位为0
				selectQrGoods.setPwdStartBit(0);
			}else{
				if(pwdStartBit == 99){
					selectQrGoods.setPwdStartBit(0);
				}else{
					selectQrGoods.setPwdStartBit(pwdStartBit + 1);
				}
			}
			
			//截取密码
			Integer currentNum = selectQrGoods.getPwdStartBit();
			String subStri = pwdLibrary.substring(6*(currentNum), 6*(currentNum+1));
			selectQrGoods.setLastPwd(subStri);
			mapper.updateByPrimaryKey(selectQrGoods);
		}
		logger.info("获取商品密码结束.......{}",EntityUtils.beanToMap(selectQrGoods));
		return selectQrGoods;
	}
	
	/**
	 * 查询商户商品列表
	 * @param request
	 * @return
	 */
	public Map<String, Object> queryMerchantGoodsList(@RequestBody Map<String, Object> params){
		logger.info("查询商户商品列表请求.......{}",params);
		//feign调用查询用户下的商户列表
		Map<String, Object> queryListByOwner = new HashMap<String, Object>();
		try {
			queryListByOwner = crmFeign.queryListByOwner(params);
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> merchantList = (List<Map<String, Object>>)queryListByOwner.get("merchantList");
			List<Map<String, Object>> respList = new ArrayList<Map<String, Object>>();
			Map<String, Object> resultMap = new HashMap<String, Object>();
			for(int i = 0; i < merchantList.size(); i++){
				Map<String, Object> respMap = new HashMap<String, Object>();
				Map<String, Object> map = merchantList.get(i);
				String platformId = (String) map.get("platformId");
				String merchantId = (String) map.get("merchantId");
				String merchantName = (String) map.get("merchantName");
				QrGoodsInfo qrGoodsInfo = new QrGoodsInfo();
				qrGoodsInfo.setPlatformId(platformId);
				qrGoodsInfo.setMerchantId(merchantId);
				List<QrGoodsInfo> selectQrGoodsInfo = mapper.select(qrGoodsInfo);
				respMap.put("qrGoodsList", selectQrGoodsInfo);
				respMap.put("merchantName", merchantName);
				respMap.put("merchantId", merchantId);
				respMap.put("platformId", platformId);
				respList.add(respMap);
			}
			resultMap.put("merchantList", respList);
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
	 * @param param
	 * @return
	 */
	public QrGoodsInfo doBindMerchant(QrThenPayStatisticsParam param) {
		logger.info("绑定商户参数。。。{}"+param);
		QrGoodsInfo goodsInfo = new QrGoodsInfo();
		goodsInfo.setGoodsId(param.getGoodsId());
		goodsInfo.setPlatformId(param.getPlatformId());
		QrGoodsInfo goodsInfo1 = mapper.selectOne(goodsInfo);
		if (goodsInfo1 != null) {
			goodsInfo1.setMerchantId(param.getMerchantId());
			mapper.updateByPrimaryKeySelective(goodsInfo1);
		}
		return goodsInfo1;
	}
	
	/**
	 * 
	 * @param param
	 * @return
	 */
	public QrGoodsInfo cancelBindMerchant(QrThenPayStatisticsParam param) {
		logger.info("取消绑定商户参数。。。{}"+param);
		QrGoodsInfo goodsInfo = new QrGoodsInfo();
		goodsInfo.setGoodsId(param.getGoodsId());
		goodsInfo.setPlatformId(param.getPlatformId());
		QrGoodsInfo goodsInfo1 = mapper.selectOne(goodsInfo);
		if (goodsInfo1 != null) {
			goodsInfo1.setMerchantId(null);
//			mapper.updateByPrimaryKeySelective(goodsInfo1);
			mapper.updateByPrimaryKey(goodsInfo1);
		}
		return goodsInfo1;	
	}
	
}